<template>
  <el-form :model="ruleForm" :rules="rules" ref="validateForm" class="login-ruleForm">
    <el-form-item prop="account">
      <el-input :placeholder="t('login.username')" v-model="ruleForm.account">
        <template #prefix>
          <icon-user theme="outline" size="16" fill="#999" />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        @keyup.enter="handleLogin"
        :placeholder="t('login.password')"
        type="password"
        v-model="ruleForm.password"
      >
        <template #prefix>
          <icon-lock theme="outline" size="16" fill="#999" />
        </template>
      </el-input>
    </el-form-item>
    
    <el-form-item prop="type">
      
      <div class="el-input el-input--prefix" data-v-619f44a6="">
        <div class="el-input__wrapper radioleft">
          <span class="el-input__prefix">
            <span class="el-input__prefix-inner">
              <icon-id-card-v theme="outline" size="16" fill="#999"/>
           </span>
          </span>
            
           <el-radio-group v-model="ruleForm.type">
               <el-radio v-for="item in userType" :label="item.key">{{item.value}}</el-radio> 
             </el-radio-group> 
       </div>
      </div>
       
    </el-form-item>
    
    <el-form-item prop="code" > 
          <el-input :placeholder="t('login.code')" v-model="ruleForm.code">
            <template #prefix>
              <icon-asterisk-key theme="outline" size="16" fill="#999" />
            </template>
          </el-input>
          <img :src="image" class="imgcss" alt="看不清,点击重新获取" title="看不清,点击重新获取" @click="fetchCaptcha"> 
    </el-form-item>
    
    <el-form-item>
      <div class="login-check">
        <el-checkbox v-model="checkedPwd">{{ t('login.rememberPwd') }}</el-checkbox>
        <el-button text type="primary">{{ t('login.forgotPwd') }}</el-button>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :loading="loading" class="login-btn" round @click="handleLogin">{{
        t('login.loginBtn')
      }}</el-button>
    </el-form-item>
    
    <el-form-item>
     <!-- <el-button type="primary"   class="login-btn" round @click="handlerRegister">商家申请入住</el-button> -->      
      <router-link :to="{path:'recruit'}" target="_blank" class="tips_nopass register">商家申请入住</router-link>
    </el-form-item>
    
    <el-form-item> 
      <router-link :to="{path:'recruitedit'}" target="_blank" class="tips_nopass">商家申请审核不通过点这里</router-link>
    </el-form-item>
    
 
    
    <el-divider>{{ t('login.thirdparty') }}</el-divider>
    <el-form-item>
      <div class="login-methods">
        <icon-wechat theme="outline" size="24" fill="#333" />
        <icon-alipay theme="outline" size="24" fill="#333" />
        <icon-github theme="outline" size="24" fill="#333" />
        <icon-twitter theme="outline" size="24" fill="#333" />
        <icon-google theme="outline" size="24" fill="#333" />
      </div>
    </el-form-item>
  </el-form>
</template>

<script>
  import { reactive, toRefs, ref, unref, watch } from 'vue';
  import { useStore } from 'vuex';
  import { useRouter } from 'vue-router';
  import { useI18n } from 'vue-i18n';
  import {codeApi} from '@/api/captcha.js'
  export default {
    setup() {
      const { t } = useI18n();
      const store = useStore();
      const router = useRouter();
      // 定义验证表单  ref="validateForm"
      const validateForm = ref(null);
       
      // 自定义方法，验证手机号
      const mobileValidator= (rule , value , callback ) => {
          if (value === '') {
            callback(new Error( t('login.mobile') ))
          } else  {
            // 验证合法性
            const  regex=/^0?(13|15|17|18|14)[0-9]{9}$/
            if(regex.test(value)){
               callback()
            }else{        
              
              callback(new Error( t('login.rules.mobileerror')))
            }        
        }
      }
       
      
      const state = reactive({
        image:'',
        // 定义表单变量
        ruleForm: {
          account: '',
          password: '',
          code: undefined,
          uuid: undefined,
          type: 'admin'
        },
        loading: false,
        checkedPwd: false,
        redirect: undefined,
        rules: {
          account: [{ required: true, message: t('login.rules.username'), trigger: 'blur' }],
          password: [{ required: true, message: t('login.rules.password'), trigger: 'blur' }],
          code:   [{ required: true, message: t('common.required'), trigger: 'blur' }],
        },
        userType: [
          {key:'admin',value:'管理员'},
          {key:'merchandiser',value:'商家'}
        ]
      });

      watch(
        () => router.currentRoute,
        ({ _value }) => {
          const route = _value;
          // 观察路由变化，判断是否有redirect自定义跳转页面
          state.redirect = (route.query && route.query.redirect) || '/';
        },
        {
          immediate: true,
        }
      );

      // 点击登录的方法
      const handleLogin = async () => {
        
        // unref 方法是专门用于获取响应式数据的非响应式原始值的
        //得到验证表单的对象
        const form = unref(validateForm);
       
        if (!form) return;        
         // vue2语法-->  this.$refs['validateForm'].validate((valid)->{});
       
        //vue3表单验证
        await form.validate((valid) => {
          if (valid) {
            state.valid = true;
            state.loading = true;
            // 调用store中user模块的login方法
            store
              .dispatch('user/login', state.ruleForm)
              .then(() => {
                const routerPath =
                  state.redirect === '/404' || state.redirect === '/401' ? '/' : state.redirect;
                  //更改路由路径
                router.push(routerPath).catch(() => {});
                state.loading = false;
              })
              .catch((e) => {
                console.log(e);
                fetchCaptcha()
                if(e && e===1131){
                  state.mobileExists=true;
                }
                state.loading = false;
              });
          }
        });
      };
     
     
     //获取验证码的方法
      function fetchCaptcha(){
        codeApi().then(resp=> { 
          state.image = resp.data.image
          state.ruleForm.uuid= resp.data.uuid
        }) 
      }
      
      //初始化调用
      fetchCaptcha()
     
     //商家申请入住
     function handlerRegister(){
       router.push({
               path: '/recruit'
           })
     }
     
     
      return {
        ...toRefs(state),
        validateForm,
        handleLogin,
        fetchCaptcha,
        handlerRegister,
        t,
      };
    },
  };
</script>
<style lang="scss" scoped>
  .radioleft{
    justify-content: flex-start;
  }
  .login-ruleForm {
    margin-top: 1rem;
    :deep(.el-input__prefix) {
      top: 2px;
      padding: 0 4px;
    }
    .login-methods {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-around;
    }
    .login-btn {
      width: 100%;
    }
    .login-check {
      width: 100%;
      display: flex;
      align-content: center;
      justify-content: space-between;
    }
    
    .imgcss{
        position: absolute;
        right: 1px;
        top: 1px;
        height: 32px;
        width:130px;
    }
    
     .tips_nopass{
       background-color: #67c23a;
       color: #fff;     
       font-size: 14px;
       border-radius: 4px;
       text-align: center;
       display: block;
       width: 100%;
       border-radius: 25px;
       text-decoration: none;
      }
      
      .tips_nopass:hover{
         background-color: #95d475;
      }
      
      .register{
        background-color: #7e9cff;
      }
      
      .register:hover{
        background-color: #a5baff;
      }
  }
</style>
